package nio;

import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @author ilongsay
 * @date: Create in 2020-03-06 14:56
 * @description: don't bb,show you code
 */
public class BuffersTest {
    public static void main(String[] args) throws Exception{
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        //绑定端口并进行启动
        serverSocketChannel.socket().bind(inetSocketAddress);

        //创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        //等客户端进行连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        //假设从客户端接收8个字节
        int messagetLenghth = 8;
        while (true) {
            int byteRead = 0;
            while (byteRead < messagetLenghth) {
                //注意这里读取的是一个数组
                long l = socketChannel.read(byteBuffers);
                //累计读取的字节数
                byteRead += l;
                System.out.println("byteRead=" + byteRead);

                Arrays.stream(byteBuffers).map(buffer ->"position"+buffer.position()+",limit="+
                        buffer.limit()).forEach(System.out::println);
            }
            //将所有的buffer进行flip
            Arrays.asList(byteBuffers).forEach(Buffer::flip);

            long byteWrite = 0;
            while (byteWrite < messagetLenghth) {
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;
            }
            //将所有的buffer进行clear
            Arrays.asList(byteBuffers).forEach(Buffer::clear);

            System.out.println("byteRead:="+byteRead+",byteWrite="+byteWrite+",messagelength"+messagetLenghth);
        }

    }
}
